package handler

import (
	"car-manage-sys/chcon"
	"car-manage-sys/modler"
	"car-manage-sys/pkg"
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")

	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不可为空",
		})
		return
	}
	var user modler.User
	err := modler.DB.Where("username=?", username).First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": "500",
			"msg":  "用户不存在",
		})
		return
	}
	if user.Password != pkg.Md5(password) {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码不正确",
		})
		return
	} else {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "登录成功",
			"data": user,
		})
		return
	}

}

func Add(c *gin.Context) {
	title := c.PostForm("title")
	content := c.PostForm("content")
	author := c.PostForm("author")

	if title == "" || content == "" || author == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段不可为空",
		})
		return
	}
	car := modler.Car{

		Title:   title,
		Content: content,
		Author:  author,
	}
	err := modler.DB.Create(&car).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "添加失败",
		})
		return
	}
	redis_key := "add" + strconv.Itoa(int(car.ID))
	var list modler.Car
	modler.DB.Where("id=?", car.ID).First(&list)
	marshal, _ := json.Marshal(&list)
	chcon.Rdb.Set(chcon.Ctx, redis_key, marshal, time.Hour*2)
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "添加成功",
	})
	return
}

func List(c *gin.Context) {
	id := c.Query("id")
	var car modler.Car
	err := modler.DB.Where("id=?", id).First(&car).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	} else {
		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "查询成功",
			"data": car,
		})
		return
	}
}

func Del(c *gin.Context) {
	id := c.Query("id")
	var car modler.Car
	err := modler.DB.Where("id=?", id).Delete(&car).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "删除失败",
		})
		return
	} else {
		redis_key := "del" + id
		chcon.Rdb.Del(chcon.Ctx, redis_key, strconv.FormatInt(int64(time.Hour*2), 10))

		c.JSON(200, gin.H{
			"code": 200,
			"msg":  "删除成功",
		})
		return
	}

}

func ListAdd(c *gin.Context) {
	var car []modler.Car
	redis_key := "listadd"
	Cont, _ := chcon.Rdb.Get(chcon.Ctx, redis_key).Result()
	if Cont == "" {
		modler.DB.Find(&car)
		marshal, _ := json.Marshal(&car)
		chcon.Rdb.Set(chcon.Ctx, redis_key, marshal, time.Hour*2)
	}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "ok",
		"data": car,
	})
	return
}
